<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>B站电影榜视频数据分析</title>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <style>
        body {
            font-family: "Microsoft YaHei", sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }

        #chart-container {
            width: 95%;
            max-width: 1400px;
            height: 750px;
            margin: 0 auto;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            padding: 20px;
            box-sizing: border-box;
        }

        .header {
            text-align: center;
            margin-bottom: 15px;
        }

        .header h1 {
            color: #333;
            margin-bottom: 5px;
        }

        .header p {
            color: #666;
            margin-top: 0;
        }

        #chart {
            width: 100%;
            height: calc(100% - 40px);
        }

        .loading {
            text-align: center;
            padding-top: 50px;
            color: #666;
            font-size: 18px;
        }

        .chart-controls {
            text-align: center;
            margin-bottom: 15px;
        }

        .chart-btn {
            padding: 8px 15px;
            margin: 0 5px;
            background-color: #f0f0f0;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .chart-btn.active {
            background-color: #58D9F9;
            color: white;
            border-color: #58D9F9;
        }

        @media (max-width: 768px) {
            #chart-container {
                height: 600px;
                padding: 10px;
            }

            .chart-btn {
                padding: 6px 10px;
                margin: 3px;
                font-size: 14px;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>B站电影榜视频数据分析</h1>
        <p>展示互动数据排行（点击切换图表 | 鼠标悬停查看详情）</p>
    </div>

    <div class="chart-controls">
        <button class="chart-btn active" data-type="likeRate">点赞率排行</button>
        <button class="chart-btn" data-type="coinRate">投币率排行</button>
        <button class="chart-btn" data-type="favoriteRate">收藏率排行</button>
        <button class="chart-btn" data-type="shareCount">转发数排行</button>
    </div>

    <div id="chart-container">
        <div id="chart">
            <div class="loading">正在加载数据...</div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const chartDom = document.getElementById('chart');
            const loadingElement = chartDom.querySelector('.loading');
            const myChart = echarts.init(chartDom);
            let processedData = [];

            fetch('../static/movie.json')
                .then(response => {
                    if (!response.ok) throw new Error('网络响应异常');
                    return response.json();
                })
                .then(rawData => {
                    processedData = processData(rawData);
                    renderChart('likeRate');
                    loadingElement.style.display = 'none';
                    window.addEventListener('resize', () => myChart.resize());
                })
                .catch(error => {
                    loadingElement.innerHTML = `
                        <div style="color:#f56c6c;">
                            <h3>数据加载失败</h3>
                            <p>${error.message}</p>
                            <p>请检查JSON路径是否正确</p>
                        </div>
                    `;
                });

            document.querySelectorAll('.chart-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    document.querySelectorAll('.chart-btn').forEach(b => b.classList.remove('active'));
                    this.classList.add('active');
                    renderChart(this.dataset.type);
                });
            });

            function processData(rawData) {
                const uniqueMap = new Map();

                rawData.forEach(item => {
                    let bvid = item.bvid || '';
                    if (!bvid && item.video_url) {
                        const match = item.video_url.match(/BV\w+/);
                        bvid = match ? match[0] : '';
                    }

                    const key = bvid || item.title;
                    if (!uniqueMap.has(key)) {
                        item.bvid = bvid;
                        uniqueMap.set(key, item);
                    }
                });

                return Array.from(uniqueMap.values()).map(item => {
                    const views = Math.max(1, parseInt(item.views));
                    const likeRate = (parseInt(item.like) / views * 100).toFixed(2);
                    const coinRate = (parseInt(item.coin) / views * 100).toFixed(2);
                    const favoriteRate = (parseInt(item.favorite) / views * 100).toFixed(2);
                    const shareCount = parseInt(item.share);

                    const displayTitle = formatTitle(item.title);

                    return {
                        name: displayTitle.short,
                        fullTitle: displayTitle.full,
                        likeRate: parseFloat(likeRate),
                        coinRate: parseFloat(coinRate),
                        favoriteRate: parseFloat(favoriteRate),
                        shareCount: shareCount,
                        raw: {
                            bvid: item.bvid,
                            views: item.views,
                            likes: item.like,
                            coins: item.coin,
                            favorites: item.favorite,
                            shares: item.share,
                            danmu: item.danmu,
                            url: item.video_url
                        }
                    };
                });
            }

            function formatTitle(title) {
                let cleanedTitle = title.replace(/【.*?】|\[.*?\]/g, '').trim();
                if (cleanedTitle.length > 15) {
                    return {
                        short: cleanedTitle.substring(0, 12) + '...',
                        full: title
                    };
                }
                return {
                    short: cleanedTitle,
                    full: title
                };
            }

            function renderChart(type) {
                if (!processedData.length) return;

                let sorted, key, name, unit, fmt;
                switch (type) {
                    case 'coinRate':
                        sorted = [...processedData].sort((a, b) => b.coinRate - a.coinRate);
                        key = 'coinRate'; name = '投币率排行'; unit = '%'; fmt = '{c}%'; break;
                    case 'favoriteRate':
                        sorted = [...processedData].sort((a, b) => b.favoriteRate - a.favoriteRate);
                        key = 'favoriteRate'; name = '收藏率排行'; unit = '%'; fmt = '{c}%'; break;
                    case 'shareCount':
                        sorted = [...processedData].sort((a, b) => b.shareCount - a.shareCount);
                        key = 'shareCount'; name = '转发数排行'; unit = '次'; fmt = '{c}'; break;
                    default:
                        sorted = [...processedData].sort((a, b) => b.likeRate - a.likeRate);
                        key = 'likeRate'; name = '点赞率排行'; unit = '%'; fmt = '{c}%';
                }

                myChart.setOption({
                    title: { text: name, left: 'center', textStyle: { fontSize: 16 } },
                    tooltip: {
                        trigger: 'item',
                        formatter: function(params) {
                            const d = sorted[params.dataIndex];
                            return `
                                <div style="font-weight:bold;font-size:16px">${d.fullTitle}</div>
                                <div style="margin-top:6px">
                                    <strong>BV号:</strong> ${d.raw.bvid}<br>
                                    <strong>播放:</strong> ${d.raw.views} |
                                    点赞: ${d.raw.likes} |
                                    投币: ${d.raw.coins} |
                                    收藏: ${d.raw.favorites} |
                                    弹幕: ${d.raw.danmu} |
                                    转发: ${d.raw.shares}
                                </div>
                                <a href="${d.raw.url}" target="_blank" style="color:#58D9F9">点击观看</a>
                            `;
                        }
                    },
                    xAxis: {
                        type: 'category',
                        data: sorted.map(d => d.name),
                        axisLabel: { rotate: 45, interval: 0 }
                    },
                    yAxis: {
                        type: 'value',
                        name: name + (unit === '%' ? ' (%)' : ' (次)'),
                        axisLabel: { formatter: unit === '%' ? '{value}%' : '{value}' }
                    },
                    series: [{
                        type: 'bar',
                        data: sorted.map(d => d[key]),
                        itemStyle: {
                            color: val => val.value > 10 ? '#FF6E76' : val.value > 5 ? '#FDDD60' : '#58D9F9',
                            borderRadius: [4, 4, 0, 0]
                        },
                        label: { show: true, position: 'top', formatter: fmt }
                    }],
                    dataZoom: [{
                        type: 'slider',
                        start: 0,
                        end: 100,
                        height: 18,
                        bottom: '8%'
                    }]
                }, true);
            }
        });
    </script>
</body>
</html>
